package com.whfc.fim.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whfc.common.exception.BizException;
import com.whfc.common.result.PageData;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.PageUtil;
import com.whfc.common.util.RegexUtil;
import com.whfc.fim.dao.FimAlgPersonImgMapper;
import com.whfc.fim.dao.FimAlgPersonMapper;
import com.whfc.fim.dto.FimPersonDTO;
import com.whfc.fim.dto.FimPersonImgDTO;
import com.whfc.fim.dto.FimPersonSyncDTO;
import com.whfc.fim.entity.FimAlgPerson;
import com.whfc.fim.entity.FimAlgPersonImg;
import com.whfc.fim.param.FimPersonParam;
import com.whfc.fim.service.FimPersonService;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Description: 人员管理 ServiceImpl
 * @Author: qzexing
 * @Version: 1.0
 * @Date: 2020/3/16 15:19
 */


@DubboService(interfaceClass = FimPersonService.class, version = "1.0.0")
public class FimPersonServiceImpl implements FimPersonService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private FimAlgPersonMapper algPersonMapper;

    @Autowired
    private FimAlgPersonImgMapper fimAlgPersonImgMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(FimPersonParam request) {
        Integer deptId = request.getDeptId();
        String idCardNo = request.getIdCardNo();
        List<Integer> personImgIdList = request.getPersonImgIdList();
        if (!RegexUtil.isIDCard(idCardNo)) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该身份证号不存在，请重新输入");
        }
        FimAlgPerson person = algPersonMapper.selectPersonByIdCardNo(deptId, idCardNo);
        if (person != null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该人员已存在，不能重复添加");
        }
        String phone = request.getPhone();
        if (!RegexUtil.isMobile(phone)) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该手机号不存在，请重新输入");
        }
        person = algPersonMapper.selectPersonByPhone(deptId, phone);
        if (person != null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该手机号已被使用，不能重复添加");
        }
        //保存人员信息
        FimAlgPerson fimPerson = new FimAlgPerson();
        fimPerson.setDeptId(deptId);
        fimPerson.setName(request.getName());
        fimPerson.setIdCardNo(idCardNo);
        fimPerson.setPhone(phone);
        fimPerson.setGuid(UUID.randomUUID().toString().replace("-", ""));
        algPersonMapper.insertSelective(fimPerson);

        //保存提交的人脸图片里面的人员信息
        fimAlgPersonImgMapper.updateImgPersonId(personImgIdList, fimPerson.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(FimPersonParam request) {
        Integer personId = request.getPersonId();
        if (personId == null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该人员ID不存在");
        }
        FimAlgPerson person = algPersonMapper.selectByPrimaryKey(personId);
        if (person == null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该人员ID不存在");
        }
        String idCardNo = request.getIdCardNo();
        if (!RegexUtil.isIDCard(idCardNo)) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该身份证号不存在，请重新输入");
        }
        if (!idCardNo.equals(person.getIdCardNo())) {
            //如果修改了身份证号，则查询该身份证是否已经添加
            FimAlgPerson p = algPersonMapper.selectPersonByIdCardNo(person.getDeptId(), request.getIdCardNo());
            if (p != null) {
                throw new BizException(ResultEnum.FAILURE.getCode(), "该人员已存在，不能重复添加");
            }
        }
        String phone = request.getPhone();
        if (!RegexUtil.isMobile(phone)) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该手机号不存在，请重新输入");
        }
        if (!phone.equals(person.getPhone())) {
            //如果修改了手机号，则查询该手机号是否已经添加
            FimAlgPerson p = algPersonMapper.selectPersonByPhone(person.getDeptId(), request.getPhone());
            if (p != null) {
                throw new BizException(ResultEnum.FAILURE.getCode(), "该手机号已被使用，不能重复添加");
            }
        }
        List<Integer> personImgIdList = request.getPersonImgIdList();
        //保存人员信息
        person.setName(request.getName());
        person.setIdCardNo(request.getIdCardNo());
        person.setPhone(request.getPhone());
        algPersonMapper.updateByPrimaryKeySelective(person);
        //关联人脸图片库里面的用户信息
        //先删除所有该用户的照片
        fimAlgPersonImgMapper.logicDelPersonImg(personId);
        //保存提交的人脸图片里面的人员信息
        fimAlgPersonImgMapper.updateImgPersonId(personImgIdList, personId);
    }

    @Override
    public PageData<FimPersonSyncDTO> list(Integer pageNum, Integer pageSize, Integer deptId) {

        PageHelper.startPage(pageNum, pageSize);
        List<FimPersonSyncDTO> personDTOList = algPersonMapper.selectPersonListByDeptId(deptId);
        PageHelper.clearPage();

        for (FimPersonSyncDTO person : personDTOList) {
            List<String> imgUrlList = fimAlgPersonImgMapper.selectImgUrlList(person.getId());
            person.setImgUrlList(imgUrlList);
        }
        return PageUtil.pageData(PageInfo.of(personDTOList));
    }

    @Override
    public PageData<FimPersonDTO> list(Integer pageNum, Integer pageSize, Integer deptId, String keyword) {

        PageHelper.startPage(pageNum, pageSize);
        List<FimPersonDTO> list = algPersonMapper.selectPersonDTOList(deptId, keyword);
        PageHelper.clearPage();

        //取出用户照片
        for (FimPersonDTO personDTO : list) {
            List<FimAlgPersonImg> imgList = fimAlgPersonImgMapper.selectPersonImgByPeronId(personDTO.getPersonId());
            List<FimPersonImgDTO> personImgList = new ArrayList<>();
            for (FimAlgPersonImg algPersonImg : imgList) {
                FimPersonImgDTO personImgDTO = new FimPersonImgDTO();
                personImgDTO.setFaceImgId(algPersonImg.getId());
                personImgDTO.setFaceImgUrl(algPersonImg.getFaceImgUrl());
                personImgList.add(personImgDTO);
            }
            personDTO.setImgList(personImgList);
        }
        return PageUtil.pageData(PageInfo.of(list));
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void del(Integer personId) {
        //删除人员图片
        fimAlgPersonImgMapper.logicDelPersonImg(personId);
        //删除人员
        algPersonMapper.logicDelPerson(personId);
    }

    @Override
    public void importEmp(List<FimPersonDTO> personList) {
        for (FimPersonDTO fimPersonDTO : personList) {
            String idCardNo = fimPersonDTO.getIdCardNo();
            FimAlgPerson existPerson = algPersonMapper.selectPersonByIdCardNo(fimPersonDTO.getDeptId(), idCardNo);
            if (existPerson != null) {
                //人员已存在，跳过此次操作
                logger.info("导入人员已存在，person:{}", fimPersonDTO);
                continue;
            }
            existPerson = algPersonMapper.selectPersonByPhone(fimPersonDTO.getDeptId(), fimPersonDTO.getPhone());
            if (existPerson != null) {
                //人员已存在，跳过此次操作
                logger.info("导入人员已存在，person:{}", fimPersonDTO);
                continue;
            }
            FimAlgPerson person = new FimAlgPerson();
            person.setDeptId(fimPersonDTO.getDeptId());
            person.setName(fimPersonDTO.getName());
            person.setPhone(fimPersonDTO.getPhone());
            person.setIdCardNo(idCardNo);
            person.setGuid(UUID.randomUUID().toString().replace("-", ""));
            algPersonMapper.insertSelective(person);
        }
    }

    @Override
    public List<String> getPersonImgByImgIds(List<Integer> imgIds) {
        return fimAlgPersonImgMapper.selectImgUrlByIds(imgIds);
    }

    @Override
    public List<FimPersonImgDTO> savePersonImg(List<String> imgUrlList) {
        List<FimPersonImgDTO> imgList = new ArrayList<>();
        for (String imgUrl : imgUrlList) {
            FimAlgPersonImg personImg = new FimAlgPersonImg();
            personImg.setFaceImgUrl(imgUrl);
            personImg.setPersonId(-1);
            fimAlgPersonImgMapper.insertSelective(personImg);
            FimPersonImgDTO personImgDTO = new FimPersonImgDTO();
            personImgDTO.setFaceImgId(personImg.getId());
            personImgDTO.setFaceImgUrl(imgUrl);
            imgList.add(personImgDTO);
        }
        return imgList;
    }
}
